import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Store } from '@ngrx/store';

import { MapState, LoadDistricts, SelectDistrict, districtsSelector } from '../../store';
import { District, UserLocation } from '../../../ngx-ol/models';

@Component({
  selector: 'ege-map-city',
  templateUrl: './city.component.html',
  styleUrls: ['./city.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class CityComponent implements OnInit {

  hotcity$: Observable<District[]>;
  provinces$: Observable<District[]>;
  loaded: boolean;
  visible: boolean = false;
  currentCity: string = '北京';

  constructor(
    private store: Store<MapState>
  ) { }

  ngOnInit() {
    this.hotcity$ = this.store.select(districtsSelector.getDistrictsHotcity);
    this.provinces$ = this.store.select(districtsSelector.getDistrictsProvinces);
    this.store.select(districtsSelector.getDistrictsLoaded).subscribe((loaded: boolean) => this.loaded = loaded);
    this.store.select(districtsSelector.getDistrictSelected)
      .subscribe((selected: UserLocation) => this.currentCity = selected ? selected.city : this.currentCity);
  }

  onVisibleChange(visible: boolean): void {
    if(visible && !this.loaded) {
      this.store.dispatch(new LoadDistricts());
    }
  }

  onClickCity(city: District): void {
    this.currentCity = city.name;
    this.store.dispatch(new SelectDistrict(city.adcode));
    this.visible = false;
  }

  getTitle(): string {
    return `当前城市：${this.currentCity}`
  }

}
